package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.enums.BaseStatus;
import com.atguigu.lease.result.ResultCodeEnum;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.constant.RedisConstant;
import com.atguigu.lease.exception.LeaseException;

import com.atguigu.lease.utils.JwtUtil;
import com.atguigu.lease.entity.SystemUser;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SystemUserService systemUserService;


    @Override
    public CaptchaVo getCaptcha() {
        //1.使用第三方工具生成验证码图片和对应的验证码字符串 【1导入依赖 | 2使用即可 | 不需放到ioc容器】
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        String text = specCaptcha.text(); //本次验证码对应的正确字符串
        System.out.println("text = " + text);
        String image = specCaptcha.toBase64();
        System.out.println("image = " + image);

        //2.把验证码字符串放到redis中 【1.随机生一个uuidkey 2.设置一个有效时间】
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key,text, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //3.将图片转成base64字符串和验证码的key一起装到vo即可
        CaptchaVo captchaVo = new CaptchaVo(image,key);
        //4.返回vo即可
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {

        //1. 输入key到redis查询验证码，如果不存在，抛异常，验证码失效，存在下一步！
        String redisCode = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (StringUtils.isEmpty(redisCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //2. 校验输入的验证码和redis中获取的验证码是否正确，不一致，验证码错误，否则，下一步！
        if (!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //3.根据账号进行数据库查询，至多查到一个用户数据，没有，抛异常，账号错误，否则，下一步！
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);
        if (systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //4.检查账号状态是不是可用，不可用，提示异常，否则，继续下一步！
        if (systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //5.将输入密码进行md5加密，进行对比，不同，抛出异常，继续下一步！
        String password = DigestUtils.md5Hex(loginVo.getPassword());
        if (!password.equals(systemUser.getPassword())){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //6.发token
        return JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }
}
